package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

import completedRDT.RDTModel;

/**
 * Model Operator
 * @author tigerzhong
 *
 */
public class ModelOperator {
    /**
     * Save model
     * @param model
     * @param localFileURl
     * @param HDFSFileURl
     */
    public static void saveModel(RDTModel model, String localFileURl, String HDFSFileURl) {
	try {
	    ObjectOutputStream outer = new ObjectOutputStream(
		    new FileOutputStream(localFileURl));
	    outer.writeObject(model);
	    outer.close();
	    HadoopUtil.localFile2HDFS(localFileURl, HDFSFileURl);
	} catch (Exception e) {
	    e.printStackTrace();
	    return;
	}
    }
    
    /**
     * Load model
     * @param modelName
     * @return RDT Model
     */
    public static RDTModel loadModel(String modelName) {
	try {
	    ObjectInputStream iner = new ObjectInputStream(new FileInputStream(
		    new File(modelName)));
	    RDTModel model = (RDTModel) (iner.readObject());
	    iner.close();
	    return model;
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
    }
    
    /**
     * Get the IP which is used as an identity number
     * 
     * @return IP String
     */
    public static String getIP() {
	try {
	    InetAddress addr = InetAddress.getLocalHost();
	    return addr.getHostAddress().toString();
	} catch (Exception e) {
	    e.printStackTrace();
	    return "";
	}
    }
    
    /**
     * Get the error and prediction result
     * @param estimationFile
     * @param labelFile
     * @param prior
     * @throws Exception
     */
    public static void decision(String estimationFile, String labelFile,
	    double prior[]) throws Exception {
	Scanner inFile = new Scanner(new File(estimationFile));
	Map<Integer, Integer> count = new TreeMap<Integer, Integer>();
	while (inFile.hasNext()) {
	    int idx = Integer.parseInt(inFile.next());
	    String est[] = inFile.next().split(",");
	    double val = Double.MIN_VALUE;
	    int label = -1;
	    for (int i = 0; i < est.length; i++) {
		double dist = Double.parseDouble(est[i]) - prior[i];
		if (dist > val) {
		    val = dist;
		    label = i;
		}
	    }
	    count.put(idx, label);
	}
	inFile.close();
	FileWriter outFile = new FileWriter(labelFile);
	Set<Integer> keys = count.keySet();
	for (Integer k : keys) {
	    outFile.write(k + "," + count.get(k) + "\n");
	}
	outFile.close();
    }
}
